<template>
  <div class="package-settings w-100% h-100%">
    <el-form label-width="100px" label-position="top" v-model="form">
      <ContentWrap :show-border="false">
        <div>
          <div class="bg-#F7F7FB p-10px rounded-6px">
            <p class="set-title">
              <span class="font-semibold">业务设置</span>
              <span class="text-#8F8F8F text-xs">（设置基本信息）</span>
            </p>
          </div>
          <div class="mt-4">
            <div>
              <el-form-item required>
                <template #label>
                  <span>商品名称</span>
                </template>
                <div class="w-[100%]">
                  <div
                    v-for="(item, index) in productThaliDOListBig"
                    :key="index"
                    class="border border-solid border-#E0E0E0 rounded-6px p-10px mb-4 w-[100%]"
                  >
                    <div class="flex items-center justify-between">
                      <p>
                        <Icon name="solar:alt-arrow-down-bold" class="mr-2px" />
                        <span>{{ item.bigName }}</span>
                      </p>
                      <p class="flex items-center cursor-pointer" @click="deleteThali(index)">
                        <Icon icon="material-symbols:delete-outline" class="mr-2px text-[red]" />
                        <span class="text-[red]">删除规格</span>
                      </p>
                    </div>
                    <div>
                      <el-table :data="item.productThaliDOList">
                        <el-table-column width="500">
                          <template #header>
                            <p>
                              <span>套餐名称</span>
                              <span class="text-[red]">*</span>
                            </p>
                          </template>
                          <template #default="{ row }">
                            <div>
                              <div class="flex items-center">
                                <div>
                                  <img
                                    class="w-[25px] h-[63px]"
                                    src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN014RjYFW1S9wOngXZ58_!!1034622205.png"
                                    alt=""
                                  />
                                </div>
                                <div class="h-[100px] flex flex-col align-center justify-center w-[500px]">
                                  <el-row :gutter="10">
                                    <el-col :span="24">
                                      <el-input
                                        v-model="row.name"
                                        placeholder="套餐"
                                        style="margin-bottom: 10px"
                                        @input="handleInput(row, index)"
                                      />
                                    </el-col>
                                  </el-row>
                                  <el-row class="mt-2" :gutter="10">
                                    <el-col :span="24">
                                      <el-input
                                        v-model="row.nameForeign"
                                        placeholder="套餐（外文）"
                                        style="margin-bottom: 10px"
                                      />
                                    </el-col>
                                  </el-row>
                                </div>
                              </div>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="name">
                          <template #header>
                            <p>
                              <span>套餐价格</span>
                              <span class="text-[red]">*</span>
                            </p>
                          </template>
                          <template #default="{ row }">
                            <el-input class="pl-2" v-model="row.originalPrice">
                              <template #suffix>元</template>
                            </el-input>
                          </template>
                        </el-table-column>
                        <el-table-column label="套餐折扣价" prop="discountedPrice">
                          <template #default="{ row }">
                            <el-input class="pl-2" v-model="row.discountedPrice">
                              <template #suffix>元</template>
                            </el-input>
                          </template>
                        </el-table-column>
                        <el-table-column label="套餐运费" prop="shippingFee">
                          <template #default="{ row }">
                            <el-input class="pl-2" v-model="row.shippingFee">
                              <template #suffix>元</template>
                            </el-input>
                          </template>
                        </el-table-column>
                        <el-table-column label="套餐图片" prop="picture" width="120">
                          <template #default="{ row }">
                            <UploadImg
                              v-model="row.picture"
                              draggable="false"
                              height="80px"
                              width="80px"
                              class="min-w-80px"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column label="是否可销售" prop="saleFlag" width="120">
                          <template #default="{ row }">
                            <el-switch
                              v-model="row.saleFlag"
                              :active-value="1"
                              :inactive-value="0"
                            />
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                  <div class="flex mt-4">
                    <el-button type="primary" color="#3721FF" plain link @click="addSpecification"
                      >+ 新增套餐</el-button
                    >
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="套餐明细">
                <div class="w-100%">
                  <div class="package-details">
                    <el-radio-group v-model="packageName">
                      <template v-for="(item, index) in productThaliDOListBig" :key="index">
                        <el-radio border :label="index + 1">{{
                          item.productThaliDOList[0].name
                        }}</el-radio>
                      </template>
                    </el-radio-group>
                  </div>
                  <template v-for="(item, index) in productThaliDOListBig" :key="index">
                    <div class="mt-4 w-100%" v-if="packageName == index + 1">
                      <el-table :data="item.productThaliDOList[0].thaliDetailList">
                        <el-table-column prop="productName" label="商品名称" width="400"/>
                        <el-table-column prop="productId" label="商品ID" v-if="false"/>
                        <el-table-column prop="cover" label="商品封面">
                          <template #default="{ row }">
                            <img :src="row.cover" style="width: 40px; height: 40px" alt="" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="number" label="数量">
                          <template #default="{ row }">
                            <el-input v-model="row.number" placeholder="请输入数量" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="independenceFlag" label="是否每个商品独立选择属性">
                          <template #default="{ row }">
                            <el-switch
                              v-model="row.independenceFlag"
                              :active-value="1"
                              :inactive-value="0"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column label="操作">
                          <template #default="{ $index }">
                            <el-button
                              type="primary"
                              color="#3721FF"
                              plain
                              link
                              @click="productDel(index, $index)"
                              >删除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <div class="mt-6" v-if="packageName == index + 1">
                      <el-button type="primary" color="#3721FF" @click="handleSelectProducts(index)"
                        >选择套餐商品</el-button
                      >
                    </div>
                  </template>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </ContentWrap>
    </el-form>
    <SelectProducts
      ref="selectProductsRef"
      :showDot="true"
      width="50%"
      title="选择套餐商品"
      @update:sel-product-list="handleUpdateSelProductList"
    />
  </div>
</template>

<script setup lang="ts">
const emit = defineEmits(['update:setPackage'])
import { ProductApi } from '@/api/product/addProduct'
const packageName = ref(1)
const selectProductsRef = ref()
const props = defineProps(['formData','activeName'])
const productThaliDOListBig = ref([
  {
    bigName: '套餐 1',
    productThaliDOList: [
      {
        name: '',
        nameForeign: '',
        isDefaultPro: false,
        originalPrice: 0,
        discountedPrice: 0,
        shippingFee: 0,
        picture: '',
        saleFlag: 1,
        thaliDetailList: [
          // {
          //   productName: '',
          //   cover: '',
          //   number: 0,
          //   independenceFlag: 0
          // }
        ]
      }
    ]
  }
])
const thaliList = ref()
const getPackageSettings = (id) => {
  ProductApi.getThaliList({ id: id }).then((res) => {
    // thaliList.value = res
    console.log(res, 'res')
    let datas = res.map((item, index) => {
      return {
        bigName: '套餐 ' + (index + 1),
        productThaliDOList: [item]
      }
    })
    productThaliDOListBig.value = datas
    console.log('getRuleAttribute', datas)
    if(datas.length ==0){
      productThaliDOListBig.value.push({
        bigName: '套餐 ' + (productThaliDOListBig.value.length + 1),
        productThaliDOList: [
          {
            name: '',
            nameForeign: '',
            isDefaultPro: false,
            originalPrice: 0,
            discountedPrice: 0,
            shippingFee: 0,
            picture: '',
            saleFlag: 1,
            thaliDetailList: [
              // {
              //   productName: '',
              //   cover: '',
              //   number: 0,
              //   independenceFlag: 0
              // }
            ]
          }
        ]
      })
    }
  })
}
// shanchu
const productDel = (index, idx) => {
  productThaliDOListBig.value[index].productThaliDOList[0].thaliDetailList.splice(idx, 1)
}

const handleUpdateSelProductList = (val) => {
  // 筛选val，只需要传需要的那个参数
  const selProductList = val.map((item) => {
    return {
      // isDefaultPro: true,//编辑的时候不用默认添加自己
      productName: item.title,
      cover: item.cover,
      number: item.number,
      independenceFlag: item.independenceFlag || 1,
      productId: item.id
    }
  })
  productThaliDOListBig.value[packageName.value - 1].productThaliDOList[0].thaliDetailList.push(...selProductList)
  let filProduct = productThaliDOListBig.value[packageName.value - 1].productThaliDOList[0].thaliDetailList
  productThaliDOListBig.value[packageName.value - 1].productThaliDOList[0].thaliDetailList = filProduct.filter((item, index) => {
    if( filProduct.findIndex((val) => val.productId === item.productId) !== index) {
      ElMessage.error('商品已存在')
    }
    return filProduct.findIndex((val) => val.productId === item.productId) === index
  })
  handleInput(productThaliDOListBig.value)
}
//
const handleSelectProducts = (index) => {
  selectProductsRef.value?.show()
}
const handleInput = (value,index) => {
  console.log(props.formData, 'props.formData.titleExternal');
  console.log(index, 'index');
  if(index >= 0){
    let newthaliDetailList = productThaliDOListBig.value[index].productThaliDOList.filter(itm=>itm.name!='')
    if(
       props.formData.thaliFlag == 1 &&
      newthaliDetailList.length >0 &&
      productThaliDOListBig.value[index].productThaliDOList[0].thaliDetailList.length == 0 && 
      !productThaliDOListBig.value[index].productThaliDOList[0].isDefaultPro
    ){
      productThaliDOListBig.value[index].productThaliDOList[0].isDefaultPro = true
      let formDataMap =  {
          productName: props.formData.title || '-',
          cover: props.formData?.cover || 'https://img.alicdn.com/imgextra/i1/1034622205/O1CN014BvoSz1S9wPMfRbY4_!!1034622205.png',
          number: null,
          independenceFlag: 1,
          productId: props.formData?.id || ''
        }
      productThaliDOListBig.value[index].productThaliDOList[0].thaliDetailList.push(formDataMap)
    }    
  }
  emit('update:setPackage', productThaliDOListBig.value)
}
const updatePackageSettings = () => {
  let flattenedData: any = []
  productThaliDOListBig.value.forEach((item) => {
    flattenedData = [
      ...flattenedData,
      ...item.productThaliDOList.map((product) => ({
        ...product,
        bigName: item.bigName
      }))
    ]
  })
  // flattenedData.map((itm) => {
  //   // 判断如果套餐价格，折扣价，套餐运费输入的整数，就加个.00
  //   if (Number(itm.originalPrice) % 1 === 0) {
  //     itm.originalPrice = itm.originalPrice + '.00'
  //   }
  //   if (Number(itm.discountedPrice) % 1 === 0) {
  //     itm.discountedPrice = itm.discountedPrice + '.00'
  //   }
  //   if (Number(itm.shippingFee) % 1 === 0) {
  //     itm.shippingFee = itm.shippingFee + '.00'
  //   }
  // })
  return flattenedData
}
const deleteThali = (index) => {
  if (productThaliDOListBig.value.length === 1) {
    ElMessage.error('至少保留一个套餐')
    return
  }
  productThaliDOListBig.value.splice(index, 1)
}
// 添加规格
const addSpecification = () => {
  productThaliDOListBig.value.push({
    bigName: '套餐 ' + (productThaliDOListBig.value.length + 1),
    productThaliDOList: [
      {
        name: '',
        nameForeign: '',
        isDefaultPro: false,
        originalPrice: 0,
        discountedPrice: 0,
        shippingFee: 0,
        picture: '',
        saleFlag: 1,
        thaliDetailList: [
          // {
          //   productName: '',
          //   cover: '',
          //   number: 0,
          //   independenceFlag: 0
          // }
        ]
      }
    ]
  })
}
onMounted(() => {  
  // let newthaliDetailList = productThaliDOListBig.value[packageName.value - 1].productThaliDOList[0].thaliDetailList.filter(itm=>itm.name!='')
  // if(!props.formData?.id &&
  //    props.formData.thaliFlag == 1 &&
  //   newthaliDetailList.length > 0
  // ){
  //   let formData =  {
  //       productName: props.formData?.productName || '',
  //       cover: props.formData?.cover || '',
  //       number: null,
  //       independenceFlag: 0,
  //       productId: props.formData?.id || ''
  //     }
  //   productThaliDOListBig.value[packageName.value - 1].productThaliDOList[0].thaliDetailList.unshift(formData)
      
  // }
  
})
watch(()=>props.activeName,(val)=>{
  productThaliDOListBig.value.forEach((item) => {
    // 更新isDefaultPro状态为true里面的thaliDetailList的值
    item.productThaliDOList.forEach((product) => {
      if(product.isDefaultPro) {
        product.thaliDetailList.forEach((thaliDetail) => {
          thaliDetail.productName =props.formData?.title
          thaliDetail.cover = props.formData?.cover
        })
      }
    })
  })
  
})
watch(
  ()=> productThaliDOListBig.value,
  () => {
    console.log('productThaliDOListBig.value', productThaliDOListBig.value)

  }
)
defineExpose({
  updatePackageSettings,
  handleInput,
  getPackageSettings
})
</script>

<style lang="scss" scoped>
.package-details {
  .el-radio {
    border-radius: 20px;
    // width: 150px;
    background: #f5f5f5;
  }
  :deep(.el-radio) {
    border-radius: 20px;
    min-width: 150px;
    // height: auto;
    background: #fff;
  }
  // :deep(.el-radio__label) {
  //   overflow: hidden;
  //   text-overflow: ellipsis;
  //   white-space: nowrap;
  // }
  :deep(.is-checked) {
    border-color: #3721ff !important;
    .el-radio__inner {
      background-color: #3721ff !important;
      border-color: #3721ff !important;
    }
    .el-radio__label {
      color: #3721ff !important;
      // white-space: normal;  /* 关键属性 */
      // word-break: break-all; /* 允许单词内换行 */
      // line-height: 1.5;     /* 调整行高 */
    }
  }
}
</style>
